<script setup>
import * as d3 from 'd3'
import { defineProps, onMounted } from 'vue'
const props = defineProps({
  width: {
    type: String
  },
  height: {
    type: String
  },
  options: {
    type: Object
  }
})
onMounted(() => {
  render()
})

// 渲染柱状图
function render() {
  const { data, title } = props.options
  // svg画布
  const svg = d3.select('#mainsvg')
  const width = +svg.attr('width')
  const height = +svg.attr('height')
  const margin = { top: 60, right: 30, bottom: 60, left: 150 }
  const innerWidth = width - margin.left - margin.right
  const innerHeight = height - margin.top - margin.bottom
  // 横坐标轴
  const xScale = d3
    .scaleLinear()
    .domain([0, d3.max(data, (d) => d.value)])
    .range([0, innerWidth])
  // 纵坐标轴
  const yScale = d3
    .scaleBand()
    .domain(data.map((d) => d.name))
    .range([0, innerHeight])
    .padding(0.3)
  const g = svg.append('g').attr('id', 'maingroup').attr('transform', `translate(${margin.left},${margin.top})`)
  const yAxis = d3.axisLeft(yScale)
  g.append('g').call(yAxis)
  const xAxis = d3.axisBottom(xScale)
  g.append('g').call(xAxis).attr('transform', `translate(0,${innerHeight})`)
  data.forEach((d) => {
    g.append('rect')
      .attr('width', xScale(d.value))
      .attr('height', yScale.bandwidth())
      .attr('fill', 'green')
      .attr('opacity', 0.7)
      .attr('y', yScale(d.name))
  })
  // 调整文本大小
  d3.selectAll('.tick text').attr('font-size', '20px')
  // 增加标题文本
  if (title.show) {
    g.append('text')
      .text(title.text)
      .attr('fill', `${title.textStyle.color}`)
      .attr('font-size', `${title.textStyle.fontSize}`)
      .attr('transform', `translate(${innerWidth / 2},0)`)
      .attr('text-anchor', 'middle')
  }
}
</script>

<template>
  <svg :width="props.width" :height="props.height" id="mainsvg" class="svgs"></svg>
</template>

<style scoped></style>
